// pages/create-room/create-room.js
const { menuManager, MENU_SOURCES } = require('../../data/menuManager.js');
const apiService = require('../../utils/apiService.js');

Page({
  data: {
    roomType: 'temporary', // temporary | permanent
    roomTitle: '',
    roomDesc: '',
    canCreate: false,
    
    // 菜单设置
    menuSource: 'default',
    menuSourceText: '默认菜单',
    showMenuSourcePicker: false,
    
    // 验证提示
    titleError: '',
    showTitleError: false
  },

  onLoad(options) {
    // 从首页传入的房间类型
    const type = options.type || 'temporary';
    this.setData({
      roomType: type,
      menuSource: 'default',
      menuSourceText: '默认菜单'
    });
    this.checkCanCreate();
  },

  // 选择房间类型
  selectRoomType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      roomType: type
    });
    this.checkCanCreate();
  },

  // 房间名称变化
  onTitleChange(e) {
    const value = e.detail;
    this.setData({
      roomTitle: value
    });
    this.checkCanCreate();
    this.validateRoomTitle(value);
  },

  // 房间描述变化
  onDescChange(e) {
    this.setData({
      roomDesc: e.detail
    });
  },

  // 检查是否可以创建
  checkCanCreate() {
    const canCreate = this.data.roomTitle && 
                     this.data.roomTitle.trim().length >= 2 && 
                     this.data.roomTitle.trim().length <= 20;
    this.setData({
      canCreate
    });
  },

  // 验证房间名称
  validateRoomTitle(value) {
    const trimmedValue = value.trim();
    
    if (trimmedValue.length === 0) {
      // 清空提示
      this.setData({
        titleError: '',
        showTitleError: false
      });
      return;
    }
    
    if (trimmedValue.length === 1) {
      this.setData({
        titleError: '房间名称至少需要2个字符',
        showTitleError: true
      });
      return;
    }
    
    if (trimmedValue.length > 20) {
      this.setData({
        titleError: '房间名称不能超过20个字符',
        showTitleError: true
      });
      return;
    }
    
    // 验证通过
    this.setData({
      titleError: '',
      showTitleError: false
    });
  },

  // 创建房间
  async createRoom() {
    // 验证房间名称
    if (!this.data.roomTitle || this.data.roomTitle.trim().length === 0) {
      wx.showToast({
        title: '请输入房间名称',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 验证房间名称长度
    if (this.data.roomTitle.trim().length < 2) {
      wx.showToast({
        title: '房间名称至少2个字符',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 验证房间名称长度上限
    if (this.data.roomTitle.trim().length > 20) {
      wx.showToast({
        title: '房间名称不能超过20个字符',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    wx.showLoading({
      title: '创建中...'
    });

    try {
      // 准备房间数据
      const roomData = {
        title: this.data.roomTitle,
        type: this.data.roomType,
        menuSource: this.data.menuSource
      };

      // 如果有描述，添加到数据中
      if (this.data.roomDesc.trim()) {
        roomData.description = this.data.roomDesc;
      }

      // 调用API创建房间
      const roomInfo = await apiService.createRoom(roomData);
      
      wx.hideLoading();
      
      // 设置房间菜单配置（本地）
      menuManager.setRoomMenuSource(roomInfo.room_id, this.data.menuSource);
      
      
      // 验证菜单配置

      wx.showToast({
        title: '创建成功',
        icon: 'success'
      });

      // 跳转到点单页面
      setTimeout(() => {
        // 保存房间信息到全局数据
        const app = getApp();
        app.globalData.currentRoom = {
          roomId: roomInfo.room_id,
          roomTitle: roomInfo.title,
          roomType: roomInfo.type,
          roomDesc: roomInfo.description
        };
        
        // 通知首页更新房间列表
        const pages = getCurrentPages();
        if (pages.length > 1) {
          const prevPage = pages[pages.length - 2];
          if (prevPage.route === 'pages/index/index') {
            prevPage.loadRoomData();
          }
        }
        
        wx.switchTab({
          url: '/pages/order/order',
          success: () => {
          },
          fail: (err) => {
            wx.showToast({
              title: '跳转失败',
              icon: 'none'
            });
          }
        });
      }, 1500);
      
    } catch (error) {
      wx.hideLoading();
      
      // 错误处理已在apiService中完成
    }
  },

  // 显示菜单来源选择器
  showMenuSourcePicker() {
    
    this.setData({
      showMenuSourcePicker: true
    }, () => {
    });
  },

  // 隐藏菜单来源选择器
  hideMenuSourcePicker() {
    this.setData({
      showMenuSourcePicker: false
    });
  },

  // 选择菜单来源
  selectMenuSource(e) {
    const source = e.currentTarget.dataset.source;
    
    // 只允许选择默认菜单
    if (source !== 'default') {
      return;
    }
    
    let sourceText = '';
    
    switch (source) {
      case 'default':
        sourceText = '默认菜单';
        break;
      case 'template':
        sourceText = '选择模板';
        break;
      case 'custom':
        sourceText = '自定义菜单';
        break;
    }
    
    this.setData({
      menuSource: source,
      menuSourceText: sourceText,
      showMenuSourcePicker: false
    });
  },

  // 显示不支持提示
  showNotSupported() {
    wx.showToast({
      title: '该功能暂不支持',
      icon: 'none',
      duration: 2000
    });
  },


  // 阻止事件冒泡
  stopPropagation(e) {
    // 阻止事件冒泡，防止点击弹层内容时关闭弹层
  }
});
